package com.safe.first.common.model;

import com.safe.first.common.constants.BaseEnum;
import com.safe.first.common.constants.CodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * @author Mickey
 * @since 2020.08.08
 */
@Data
@ApiModel(value = "接口返回对象", description = "接口返回对象")
public class R<T> implements Serializable {

    @ApiModelProperty("请求id")
    private String traceId;
    @ApiModelProperty("成功标志")
    private boolean success;
    @ApiModelProperty("时间戳")
    private Long timestamp = System.currentTimeMillis();
    @ApiModelProperty("返回代码")
    private Integer code;
    @ApiModelProperty("返回处理消息")
    private String msg;
    @ApiModelProperty("返回数据对象")
    private T data;

    public static <T> R<T> OK() {
        R<T> r = new R<>();
        r.success = true;
        r.setCode(CodeEnum.SUCCESS.getCode());
        r.setMsg(CodeEnum.SUCCESS.getName());
        r.setTraceId(MDC.get("TRACE_ID"));
        return r;
    }

    public static <T> R<T> OK(T data) {
        R<T> r = new R<>();
        r.setSuccess(true);
        r.setCode(CodeEnum.SUCCESS.getCode());
        r.setData(data);
        r.setMsg(CodeEnum.SUCCESS.getName());
        return r;
    }

    public static R<?> ofError() {
        R<?> r = new R<>();
        r.success = false;
        r.setCode(CodeEnum.FAIL.getCode());
        r.setMsg(CodeEnum.FAIL.getName());
        return r;
    }

    public static R<?> ofError(BaseEnum<?> codeEnum) {
        R<?> r = new R<>();
        r.success = false;
        r.setCode(codeEnum.getCode());
        r.setMsg(codeEnum.getName());
        return r;
    }

    public static R<?> ofError(String msg) {
        R<?> r = new R<>();
        r.success = false;
        r.setTraceId(MDC.get("TRACE_ID"));
        r.setCode(CodeEnum.FAIL.getCode());
        r.setMsg(msg);
        return r;
    }
}
